const http = require('http');
const fs = require("fs");

const path = require("path");

http.createServer((req,res)=>{
    if(req.url=="/"){
        var fileContent = fs.readFileSync("./upload.html")
        res.writeHead(200, {"Content-Type":"text/html;charset=utf8"})
        res.end(fileContent)
    }
    else if(req.url == "/upload"){
        var str = "";
        req.setEncoding("binary"); //设置编码格式为二进制
        req.on("data", (chunk) => {
            str += chunk;
        })
        req.on("end", () => {
            console.log(str);
            var arr = str.split("\r\n") //用换行切割成数组
            var imgArr = arr.slice(4, arr.length-2); //从数组的第4个切割到数组的倒数第2个
            var imgStr = imgArr.join("\r\n"); //将数组用换行隔开拼成字符串
            var buf = Buffer.from(imgStr, "binary"); //从一个二进制字符串转换为Buffer数据
            fs.writeFileSync(path.join(__dirname,"/img/1.png"), buf, {"encoding":"binary"})
            
        })
    }
    
    
    
}).listen(8081);

console.log("server is listening 8081")